package com.example.minimusicdemo;

import java.util.ArrayList;

//import sharevideo.SendFilesFragment;

import adjust_volume.ApplierChain;
import adjust_volume.DrawerOpener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.example.project22_editingmediaplayer.LayoutAllSong;
import com.example.project22_editingmediaplayer.LayoutRecent;
import com.example.project22_editingmediaplayer.MainActivity;
import com.example.project22_editingmediaplayer.R;
import com.example.project22_editingmediaplayer.objects.SongObject;
import com.example.project22_editingmediaplayer.resource.SongResource;
import com.example.project22_editingmediaplayer.service.MediaService;
import com.example.project22_editingmediaplayer.service.MediaService.LocalMediaBinder;

public class Fragment_playmain extends Fragment implements
		OnSeekBarChangeListener {

	public static MediaService mService_play;
	boolean mBound_play;
	private static SongUtility utils;

	static ImageButton button_mainplay;
	ImageButton audio_player_prev;
	ImageButton audio_player_next;
	ImageButton audio_player_shuffle;
	ImageButton audio_player_repeat;
	static SeekBar progress_play;
	private static Handler mHandler = new Handler();
	public static TextView audio_player_current_time, audio_player_total_time,
			audio_player_track, audio_player_album_artist;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_playmain, container,
				false);
		setHasOptionsMenu(true);

		Intent i = new Intent(getActivity(), MediaService.class);
		getActivity().bindService(i, connection, Context.BIND_AUTO_CREATE);

		button_mainplay = (ImageButton) rootView
				.findViewById(R.id.audio_player_play);
		audio_player_shuffle = (ImageButton) rootView
				.findViewById(R.id.audio_player_shuffle);
		audio_player_prev = (ImageButton) rootView
				.findViewById(R.id.audio_player_prev);
		audio_player_next = (ImageButton) rootView
				.findViewById(R.id.audio_player_next);
		audio_player_repeat = (ImageButton) rootView
				.findViewById(R.id.audio_player_repeat);

		progress_play = (SeekBar) rootView.findViewById(R.id.progress_play);
		audio_player_current_time = (TextView) rootView
				.findViewById(R.id.audio_player_current_time);
		audio_player_total_time = (TextView) rootView
				.findViewById(R.id.audio_player_total_time);
		audio_player_track = (TextView) rootView
				.findViewById(R.id.audio_player_track);
		audio_player_album_artist = (TextView) rootView
				.findViewById(R.id.audio_player_album_artist);

		utils = new SongUtility();
		if (MainActivity.mService.isShuffle()) {

			audio_player_shuffle
					.setImageResource(R.drawable.apollo_holo_light_shuffle_on);
		} else {

			audio_player_shuffle
					.setImageResource(R.drawable.apollo_holo_light_shuffle_normal);

		}

		if (MainActivity.mService.isRepeat()) {

			audio_player_repeat
					.setImageResource(R.drawable.apollo_holo_light_repeat_all);
		} else {

			audio_player_repeat
					.setImageResource(R.drawable.apollo_holo_light_repeat_normal);

		}

		audio_player_shuffle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				if (MainActivity.mService.isShuffle()) {
					MainActivity.mService.setShuffle(false);
					audio_player_shuffle
							.setImageResource(R.drawable.apollo_holo_light_shuffle_normal);
				} else {
					// make repeat to true
					MainActivity.mService.setRepeat(false);
					MainActivity.mService.setShuffle(true);
					audio_player_shuffle
							.setImageResource(R.drawable.apollo_holo_light_shuffle_on);
					audio_player_repeat
							.setImageResource(R.drawable.apollo_holo_light_repeat_normal);
				}

			}
		});
		audio_player_repeat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (MainActivity.mService.isRepeat()) {
					MainActivity.mService.setRepeat(false);
					audio_player_repeat
							.setImageResource(R.drawable.apollo_holo_light_repeat_normal);
				} else {
					// make repeat to true
					MainActivity.mService.setShuffle(false);
					MainActivity.mService.setRepeat(true);
					audio_player_repeat
							.setImageResource(R.drawable.apollo_holo_light_repeat_all);
					audio_player_shuffle
							.setImageResource(R.drawable.apollo_holo_light_shuffle_normal);
				}

			}
		});
		progress_play.setOnSeekBarChangeListener(this);

		if (MainActivity.mService.getMediaPlayer() != null) {
			if (MainActivity.mService.getMediaPlayer().isPlaying()) {

				button_mainplay
						.setImageResource(R.drawable.apollo_holo_light_pause);
			} else {

				button_mainplay
						.setImageResource(R.drawable.apollo_holo_light_play);
			}
		}
		button_mainplay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// MainActivity.mService.flag_first = false;
				if (mService_play.getMediaPlayer() != null) {
					updateProgressBar();
					if (mService_play.getMediaPlayer().isPlaying()) {
						MainActivity.mService.getMediaPlayer().pause();
						button_mainplay
								.setImageResource(R.drawable.apollo_holo_light_play);
						MainActivity.btnPlay
								.setImageResource(R.drawable.apollo_holo_light_play);
						MainActivity.mService.showNotification(
								MainActivity.mService.getIndex(),
								SongResource.listSong.get(MainActivity.mService
										.getIndex()));
					//	Main_play.viewcontrolvolume.setVisibility(View.VISIBLE);

					} else {
						mService_play.getMediaPlayer().start();
						button_mainplay
								.setImageResource(R.drawable.apollo_holo_light_pause);
						MainActivity.btnPlay
								.setImageResource(R.drawable.apollo_holo_light_pause);
						MainActivity.mService.showNotification(
								MainActivity.mService.getIndex(),
								SongResource.listSong.get(MainActivity.mService
										.getIndex()));
					}
				}
			}
		});
		audio_player_prev.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.mService.getlistsong() != null) {
					mService_play.previusSong();
					button_mainplay
							.setImageResource(R.drawable.apollo_holo_light_pause);
					MainActivity.btnPlay
							.setImageResource(R.drawable.apollo_holo_light_pause);

					audio_player_track.setText(MainActivity.mService.getsong()
							.get_name());
					audio_player_album_artist.setText(MainActivity.mService
							.getsong().get_artist());
					MainActivity.namesong.setText(MainActivity.mService
							.getsong().get_name());
					MainActivity.singer.setText(MainActivity.mService.getsong()
							.get_artist());

					SongResource.listSong.get(
							MainActivity.mService.getlastIndex()).set_isplay(
							false);
					SongResource.listSong.get(MainActivity.mService.getIndex())
							.set_isplay(true);
					Fragment_playlist.ad_playlist.notifyDataSetChanged();

				} else {

					if (mService_play.getMediaPlayer() != null) {
						if (mService_play.getMediaPlayer().isPlaying()) {
							MainActivity.mService.getMediaPlayer().pause();
							button_mainplay
									.setImageResource(R.drawable.apollo_holo_light_play);
							MainActivity.btnPlay
									.setImageResource(R.drawable.apollo_holo_light_play);
							MainActivity.mService.showNotification(
									MainActivity.mService.getIndex(),
									SongResource.listSong
											.get(MainActivity.mService
													.getIndex()));

						}

					}

				}

			}
		});
		audio_player_next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.mService.getlistsong() != null) {

					mService_play.nextSong();
					button_mainplay
							.setImageResource(R.drawable.apollo_holo_light_pause);
					MainActivity.btnPlay
							.setImageResource(R.drawable.apollo_holo_light_pause);

					audio_player_track.setText(MainActivity.mService.getsong()
							.get_name());
					audio_player_album_artist.setText(MainActivity.mService
							.getsong().get_artist());

					MainActivity.namesong.setText(MainActivity.mService
							.getsong().get_name());
					MainActivity.singer.setText(MainActivity.mService.getsong()
							.get_artist());

					SongResource.listSong.get(
							MainActivity.mService.getlastIndex()).set_isplay(
							false);
					SongResource.listSong.get(MainActivity.mService.getIndex())
							.set_isplay(true);
					Fragment_playlist.ad_playlist.notifyDataSetChanged();
				} else {

					if (mService_play.getMediaPlayer() != null) {
						if (mService_play.getMediaPlayer().isPlaying()) {
							MainActivity.mService.getMediaPlayer().pause();
							button_mainplay
									.setImageResource(R.drawable.apollo_holo_light_play);
							MainActivity.btnPlay
									.setImageResource(R.drawable.apollo_holo_light_play);
							MainActivity.mService.showNotification(
									MainActivity.mService.getIndex(),
									SongResource.listSong
											.get(MainActivity.mService
													.getIndex()));

						}

					}

				}
			}
		});
		progress_play.setMax(100);
		if (!MainActivity.mService.flag_first) {
			updateProgressBar();

			audio_player_track.setText(MainActivity.mService.getsong()
					.get_name());
			audio_player_album_artist.setText(MainActivity.mService.getsong()
					.get_artist());

		}

		return rootView;
	}

	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mBound_play = false;
			mService_play = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			LocalMediaBinder binder = (LocalMediaBinder) service;
			mService_play = binder.getMediaService();
			mBound_play = true;

		}
	};

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);

		menu.clear();
		inflater.inflate(R.menu.menuemotion, menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {/*
		case R.id.share:

						 final float playbackSpeed=1.5f; final SoundPool soundPool = new
			  SoundPool(4, AudioManager.STREAM_MUSIC, 100);
			  
			  final int soundId =
			  soundPool.load(MainActivity.mService.getsong().get_path(), 1);
			  AudioManager mgr = (AudioManager)
			  getSystemService(Context.AUDIO_SERVICE); final float volume =
			  mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			  
			  soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
			  {
			  
			  @Override public void onLoadComplete(SoundPool arg0, int arg1,
			  int arg2) { soundPool.play(soundId, volume, volume, 1, 0,
			  playbackSpeed); } });
			 

			break;

		default:
			break;
		*/}
		return super.onOptionsItemSelected(item);

	}

	private AudioManager getSystemService(String audioService) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = MainActivity.mService.getMediaPlayer()
				.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(),
				totalDuration);
		MainActivity.mService.getMediaPlayer().seekTo(currentPosition);
		updateProgressBar();

	}

	public static void updateProgressBar() {
		mHandler.postDelayed(mUpdateTimeTask, 100);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	private static Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			if (MainActivity.mService.getMediaPlayer().isPlaying()) {
				long totalDuration = MainActivity.mService.getMediaPlayer()
						.getDuration();
				long currentDuration = MainActivity.mService.getMediaPlayer()
						.getCurrentPosition();

				// Displaying Total Duration time
				audio_player_total_time.setText(""
						+ utils.milliSecondsToTimer(totalDuration));
				// Displaying time completed playing
				audio_player_current_time.setText(""
						+ utils.milliSecondsToTimer(currentDuration));

				// Updating progress bar
				int progress = (int) (utils.getProgressPercentage(
						currentDuration, totalDuration));
				progress_play.setProgress(progress);
				mHandler.postDelayed(this, 100);
			} else {
			}
		}
	};

}